<template>
  <div class="category">
    <h1>{{ id ? "编辑" : "新建" }}分类</h1>
    <el-form label-width="120px" v-model="form" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select v-model="form.categories" multiple>
          <el-option
            v-for="item in categories"
            :key="item._id"
            :value="item._id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="详情">
        <vue-editor
          v-model="form.body"
          @image-added="handleImageAdded"
          useCustomImageHandler
        ></vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
/* eslint-disable */
export default {
  name: "ArticleEdit",
  components: {
    VueEditor,
  },
  props: {
    id: {},
  },
  data() {
    return {
      form: {},
      categories: [], // 所属分类选项
    };
  },
  created() {
    this.id && this.edit(); // 判断是否有id,有则执行后面的方法
    this.getCategories();
  },
  mounted() {},
  methods: {
    // 获得分类列表
    save() {
      let res;
      if (this.id) {
        // 如果存在id，则调用编辑的接口
        res = this.$http.put(`rest/articles/${this.id}`, this.form); // 调用这个接口
      } else {
        res = this.$http.post(`rest/articles`, this.form); // 调用这个接口
      }
      this.$router.push("/articles/list"); // 路由跳转
      this.$message({
        type: "success",
        message: "保存成功！！！",
      });
    },
    // 获得详情
    async edit() {
      const res = await this.$http.get(`rest/articles/${this.id}`); // 调用接口
      this.form = res.data; // 将查询到的数据返回到页面
    },
    // 获得详情
    async getCategories() {
      const res = await this.$http.get(`rest/categories`); // 调用接口
      this.categories = res.data; // 将查询到的分类数据返回给数组
    },
    // 处理上传图片
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      const res =  await this.$http.post('upload', formData)
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader(); // 重置上传器
    },
  },
};
</script>

<style scoped></style>
